import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;


/**
 * @author： pang-yun
 * @date： 2021-11-02 11:36
 * 功能目的 ：用于
 */

@Slf4j
public class Mq {
    public static void main(String[] args) throws InterruptedException {
        MessageQueueA messageQueueA = new MessageQueueA(2);

        for (int i = 0; i < 3; i++) {
            int id = i;
            new Thread(() -> {
                messageQueueA.put(new Message(id, "   " + id));
            }, "生产").start();
        }

        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            while (true) {
                messageQueueA.take();
            }
        }).start();

    }
}


@Slf4j
class MessageQueueA {
    private LinkedList<Message> list = new LinkedList<>();
    private int capacity;

    public MessageQueueA(int capacity) {
        this.capacity = capacity;
    }


    public void put(Message message) {
        synchronized (list) {
            while (list.size() == capacity) {
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.addLast(message);
            log.info("放：{}", message);
            list.notifyAll();
        }
    }

    public Message take() {
        synchronized (list) {
            while (list.isEmpty()) {
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Message message = list.removeFirst();
            list.notifyAll();
            log.info("取：{}", message);
            return message;
        }
    }
}


@Data
@AllArgsConstructor
final class Message {
    private int id;
    private Object value;
}
